package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"lianxi3/cache"
	"lianxi3/model"
	"lianxi3/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_ket := "user_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_ket).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登陆",
		})
		return
	}
	var user model.User
	if err := model.DB.Where("username=?", username).First(&user).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_ket)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_ket, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误，封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
	return
}

func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := model.UserRole{
		Uid: uid,
		Rid: rid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "用户和角色关联成功",
	})
	return
}
func RoleNodeAdd(c *gin.Context) {
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "角色与权限关联成功",
	})
	return
}
func UserRoleList(c *gin.Context) {
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles on roles.id=user_roles.rid
		  WHERE user_roles.uid=1
	*/
	uid := c.Query("uid")
	var data []model.Role
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles on roles.id=user_roles.rid").
		Where("user_roles.uid=?", uid).
		Debug().Find(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "角色查询成功",
		"data": data,
	})
	return
}
func RoleNodeList(c *gin.Context) {
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes on nodes.id=role_nodes.nid
		  WHERE role_nodes.rid=1
	*/
	rid := c.Query("rid")
	var data []model.Node
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes on nodes.id=role_nodes.nid").
		Where("role_nodes.rid=?", rid).
		Debug().Find(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "权限查询成功",
		"data": data,
	})
	return
}

func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var total int64
	model.DB.Model(&model.User{}).Count(&total)

	var data []model.User
	redis_key := "user_list_" + strconv.Itoa(int(page))
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Debug().Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"total": total,
		"data":  data,
	})
	return
}
func UserDetail(c *gin.Context) {
	id := c.Query("id")
	var data model.User
	redis_key := "user_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Debug().First(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情查询成功",
		"data": data,
	})
	return
}
func UserDelete(c *gin.Context) {
	id := c.Query("id")
	model.DB.Delete(&model.User{}, id)
	redis_key := "user_detail_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
